package com.wqnmdb.im.utils;

import cn.hutool.core.util.HexUtil;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 */
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class MD5Util {

    private final static String MD5 = "MD5";

    private final static String SHA = "SHA";

    private final static String ENCODING = "UTF-8";

    /***
     * MD5算法
     */
    public static String md5(String inStr){
        String md5Code = "";
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance(MD5).digest(inStr.getBytes(ENCODING));
            md5Code = new BigInteger(1, secretBytes).toString(16);

            // 如果生成数字未满32位，需要前面补0
            for (int i = 0; i < 32 - md5Code.length(); i++) {
                md5Code = "0" + md5Code;
            }
        } catch (Exception e) {
            throw new RuntimeException("没有这个md5算法！");
        }finally {
            return md5Code;
        }
    }

    /**
     * 16位MD5
     * @param inStr
     * @return
     */
    public static String md5Short(String inStr) {
        return md5(inStr).substring(8, 24);
    }

    /**
     * SHA1(安全哈希算法)
     * @param inStr
     * @return
     */
    public static String hash(String inStr) {
        String shaCode = "";
        MessageDigest messageDigest = null;
        try {
            // 此处的sha代表sha1
            messageDigest = MessageDigest.getInstance(SHA);
            // 调用digest方法，进行加密操作
            byte[] cipherBytes = messageDigest.digest(inStr.getBytes(ENCODING));
            shaCode = HexUtil.encodeHexStr(cipherBytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }finally {
            return shaCode;
        }
    }
}
